import subprocess
import os
import subprocess
import os


def convert_vob_to_mp4(vob_file, output_dir, segments):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

        # 转换 VOB 文件为 MP4，设置编码参数以保留高质量
    mp4_file = os.path.join(output_dir, os.path.basename(vob_file).replace('.VOB', '.mp4'))
    subprocess.run(['ffmpeg', '-i', vob_file, '-c:v', 'libx264', '-preset', 'slow', '-crf', '22', mp4_file, '-y'],
                   check=True)

    for i, segment in enumerate(segments):
        start_time = segment['start']
        duration = segment['duration']
        segment_file = os.path.join(output_dir, f'segment_{i + 1}.mp4')

        # 分割视频，保持编码格式
        subprocess.run(
            ['ffmpeg', '-i', mp4_file, '-ss', str(start_time), '-t', str(duration), '-c:v', 'copy', segment_file, '-y'],
            check=True)


if __name__ == '__main__':
    # VOB 视频文件路径
    vob_file = 'G:\\BaiduNetdiskDownload\\猫和老鼠14DVD194集\\猫和老鼠01\\VIDEO_TS\\VTS_01_1.VOB'
    # 输出目录
    output_dir = 'G:\\BaiduNetdiskDownload\\猫和老鼠14DVD194集\\猫和老鼠01\\out_mp4'
    # 小节定义(start time in seconds and duration in seconds)
    ones = 7*60 # 每小节7分钟
    segments = [
        #{'start': 0, 'duration': ones},  # 第一小节，0秒开始，持续10秒
        #{'start': 10, 'duration': ones},  # 第二小节，10秒开始，持续15秒
        # 可以根据需要添加更多小节
    ]
    for i in range(0,20):
        item ={
            'start':i*ones,
            'duration':(i+1)*ones
        }
        segments.append(item)

    convert_vob_to_mp4(vob_file, output_dir, segments)